package com.op.teachingliteapp.sender.handler;

import com.op.teachingliteapp.util.ScreenCapUtil;

import android.util.Log;
import android.view.View;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


/**
 * Created by Genji on 2015/5/10.
 */
public class ScreenSendHandler extends ChannelHandlerAdapter {


    private View view;

    public ScreenSendHandler(View view) {
        this.view = view;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	Log.i("channelActive", "----------defult-----------");
        ByteBuf screencap = null;
        byte[] bytes =null;
        Log.i("channelActive", "----------start-----------");

        if (view != null) {
            bytes = ScreenCapUtil.screenCapToByte(view);
        } else {
            bytes= new byte[10];
        }


        Log.i("channelActive", "-----length-----"+bytes.length+"-----------");
        screencap = Unpooled.buffer(bytes.length);

        screencap.writeInt(bytes.length);
        screencap.writeBytes(bytes);
        ctx.writeAndFlush(screencap);


        Log.i("channelActive", "----------end-----------");
       
        ctx.close();


    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        ctx.close();
    }
}
